// pages/detailProject/detailProject.js
import { 
  queryResumeService,
  deleteResumeService
} from "../../api/resume";

Page({
  data: {
    projectDetail: null,
    loading: true,
    projectId: null,
    showDeleteButton: true
  },

  onLoad(options) {
    console.log("页面参数:", options);
    if (options.id) {
      this.setData({
        projectId: parseInt(options.id),
      });

      const fromUserJoinProject = options.fromUserJoinProject === 'true';
      this.setData({
        showDeleteButton: !fromUserJoinProject
      });
      
      this.getProjectDetail();
    } else {
      wx.showToast({
        title: "项目ID缺失",
        icon: "error",
        duration: 2000,
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    }
  },

  getProjectDetail() {
    if (!this.data.projectId) {
      wx.showToast({
        title: "项目ID不存在",
        icon: "error",
        duration: 2000,
      });
      return;
    }

    this.setData({
      loading: true,
    });

    queryResumeService(this.data.projectId)
      .then((res) => {
        console.log("获取简历详情响应:", res);
        if (res.code === 200) {
          const projectDetail = this.processProjectData(res.data);
          
          this.setData({
            projectDetail: projectDetail,
            loading: false,
          });
        } else {
          console.log("API响应状态码不是200：", res.code);
          wx.showToast({
            title: res.message || `请求失败: ${res.code}`,
            icon: "none",
          });
          this.setData({
            loading: false,
          });
        }
      })
      .catch((err) => {
        console.error("获取简历详情失败：", err);
        wx.showToast({
          title: "网络异常，请重试",
          icon: "none",
        });
        this.setData({
          loading: false,
        });
      });
  },

  processProjectData(data) {
    const joinTime = data.joinTime ? data.joinTime.split(' ')[0] : '';
    let endTime = '';
    
    if (!data.endTime || data.endTime === "至今") {
      endTime = "至今";
    } else {
      endTime = data.endTime.split(' ')[0];
    }
    
    let duration = '';
    if (joinTime && endTime && endTime !== "至今") {
      const startDate = new Date(joinTime);
      const endDate = new Date(endTime);
      const timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
      const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
      duration = diffDays;
    }
    
    let projectBelief = data.projectBelief;
    if (projectBelief === "1") {
      projectBelief = "落地";
    } else if (projectBelief === "2") {
      projectBelief = "获奖";
    } else if (projectBelief === "3") {
      projectBelief = "学习";
    }

    return {
      ...data,
      joinTime,
      endTime,
      duration,
      projectBelief
    };
  },

  deleteProject() {
    if (!this.data.projectId) {
      wx.showToast({
        title: "项目ID不存在",
        icon: "error",
        duration: 2000,
      });
      return;
    }

    wx.showModal({
      title: "确认删除",
      content: "确定要删除这个项目吗？删除后无法恢复！",
      confirmColor: "#fa5151",
      success: (res) => {
        if (res.confirm) {
          this.executeDeleteProject();
        }
      },
    });
  },

  // executeDeleteProject() {
  //   wx.showLoading({
  //     title: "删除中...",
  //     mask: true,
  //   });

  //   deleteResumeService(this.data.projectId)
  //     .then((res) => {
  //       console.log("删除项目响应：", res);
  //       wx.hideLoading();

  //       if (res.code === 200) {
  //         wx.showToast({
  //           title: "删除成功",
  //           icon: "success",
  //           duration: 1500,
  //           success: () => {
  //             // 通知上一页刷新数据
  //             const pages = getCurrentPages();
  //             if (pages.length > 1) {
  //               const prevPage = pages[pages.length - 2];
  //               // 确保调用刷新方法
  //               if (prevPage && typeof prevPage.refreshData === 'function') {
  //                 prevPage.refreshData();
  //               } else if (prevPage && typeof prevPage.getMyResumeProjects === 'function') {
  //                 // 如果没有 refreshData 方法，直接调用 getMyResumeProjects
  //                 prevPage.getMyResumeProjects();
  //               }
  //             }
              
  //             setTimeout(() => {
  //               wx.navigateBack();
  //             }, 1000);
  //           }
  //         });
  //       } else {
  //         wx.showModal({
  //           title: "",
  //           content: res.message || `删除失败: ${res.code}`,
  //           showCancel: false,
  //           confirmText: "确定",
  //         });
  //       }
  //     })
  //     .catch((err) => {
  //       console.error("删除项目失败：", err);
  //       wx.hideLoading();
  //       wx.showModal({
  //         title: "",
  //         content: err.message || "网络异常，请重试",
  //         showCancel: false,
  //         confirmText: "确定",
  //       });
  //     });
  // },

  executeDeleteProject() {
  wx.showLoading({
    title: "删除中...",
    mask: true,
  });

    deleteResumeService(this.data.projectId)
      .then((res) => {
        console.log("删除项目响应：", res);
        wx.hideLoading();

        if (res.code === 200) {
          // 使用 wx.showModal 替代 wx.showToast，确保用户能看到提示
          wx.showModal({
            title: '删除成功',
            content: '项目已从您的简历中移除',
            showCancel: false,
            confirmText: '确定',
            success: (result) => {
              // 用户点击确定后才返回上一页
              if (result.confirm) {
                // 通知上一页刷新数据
                const pages = getCurrentPages();
                if (pages.length > 1) {
                  const prevPage = pages[pages.length - 2];
                  // 确保调用刷新方法
                  if (prevPage && typeof prevPage.refreshData === 'function') {
                    prevPage.refreshData();
                  } else if (prevPage && typeof prevPage.getMyResumeProjects === 'function') {
                    // 如果没有 refreshData 方法，直接调用 getMyResumeProjects
                    prevPage.getMyResumeProjects();
                  }
                }
                
                wx.navigateBack();
              }
            }
          });
        } else {
          wx.showModal({
            title: "",
            content: res.message || `删除失败: ${res.code}`,
            showCancel: false,
            confirmText: "确定",
          });
        }
      })
      .catch((err) => {
        console.error("删除项目失败：", err);
        wx.hideLoading();
        wx.showModal({
          title: "",
          content: err.message || "网络异常，请重试",
          showCancel: false,
          confirmText: "确定",
        });
      });
  },
  onReady() {

  },

  onShow() {

  },
})